const https = require('https');
const SQLHelper = require('./SQLHelper');
///雪花算法生成id
const snowflake = require('./snowflake')
const {formatTime} = require('./util')
///解析body中间件


const multer = require('multer')
const storage = multer.diskStorage({
    destination: './uploads',
    filename: function (req, file, cb) {
        ///获取图片类型
        console.log(file)
        let fileType = file.originalname.split('.')
        fileType = fileType[fileType.length - 1]
        cb(null,snowflake() + '.' + fileType)
    }
})

const upload = multer({ storage:storage })


module.exports = function(app){
 //登录拦截中间件
 function loginRouter(req,res,next){
    if(req.method.toUpperCase() == 'OPTIONS'){
        next()
        return;
    }
    let token = req.headers.token
    if(token){
        SQLHelper(`select * from session where id = ${token} and state = 1`).then(ret => {
            if(ret.length){
                let session = ret[0]
                //2h
                if(new Date().getTime() - session.createTime < 2*60*60*1000){
                    req.session = {
                        userId:session.userId,
                        userName:session.userName
                    }
                    next()
                }else{
                    res.status(400).send({errorMsg:'登录超时'})
                }              
            }else{
                res.status(400).send({errorMsg:'当前用户未登录'})
            }
        })
    }else{
        res.status(400).send({errorMsg:'缺少token,请先登录'})
    }
}

    ///让初登陆以为的所有小程序接口都先验证登陆
    app.use('/admin',loginRouter)

    ///文件上传
    app.post('/upload',upload.single('file'),(req,res) => {
        res.send(req.file)
    })
    
  ///后台管理端登陆
  app.post('/login',(req,res) =>{
    let userName = req.body.userName
    let passWord = req.body.passWord
    ///用户名和密码必须同时存在
    if(userName && passWord){
        SQLHelper(`
            select * from user where userName = '${userName}'
        `).then(users => {///此时user是一个列表，所以 users
            if(users.length){///存在时为正常登陆
                let user = users[0]
                if(passWord == user.passWord){///正常登陆
                    let token = snowflake()
                    ///缓存token到session表
                    SQLHelper(`
                    INSERT INTO session(id,userId,userName,inTime,createTime,platform) 
                    VALUES(${token},'${user._id}','${user.nickName}','${formatTime(new Date())}',${new Date().getTime()},'admin')
                    `).then(ret => {
                        res.send({
                            nickName:user.nickName,
                            token,
                            avatarUrl:user.photo,
                            _id:user._id
                        })
                    })
                }else{///非正常登陆，结果返回给前端
                    res.send({errorMsg:'密码错误'})
                }
            }else{
                res.send({errorMsg:'当前用户不存在'})
            }
        })
    }else{
        res.send({errorMsg:'请输入用户名和密码'})
    }
})
    //退出登录
    app.get('/admin/logout',(req,res) => {
        SQLHelper(`
            update session set outTime = '${formatTime(new Date())}',state = 0
            where id = '${req.headers.token}'
        `).then(ret => {
            res.send({msg:'退出登录成功'})
        })
    })

    /// 修改密码
    app.post('/admin/changePassWord',(req,res) => {
        let userId = req.session.userId
        let passWord = req.body.passWord
        let newPassWord = req.body.newPassWord
        if(passWord && newPassWord){
            ///查询用户
            SQLHelper(`select passWord from user where _id = '${userId}'`).then(users => {
                let user = users[0]
                ///对比原密码
                if(user.passWord == passWord){
                    ///修改密码
                    SQLHelper(`update user set passWord = '${newPassWord}' where _id = '${userId}'`).then(ret => {
                        res.send({msg:'修改密码成功'})
                    })
                }else{
                    res.send({errorMsg:'原密码错误'})
                }
            })
        }else{
            res.send({errorMsg:'原密码和新密码不能为空'})
        }
    })

    ///分页获取首页项目列表
    ///pageSize 每页大小 默认10
    ///pageNum 当前页 默认1
    ///type类型 非必填 banner，轮播图 category，分类 recomend,为你推荐 不填搜索全部
    app.get('/admin/index',(req,res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum -1) * pageSize
        let title = req.query.title
        let type = req.query.type 
        let whereSql = 'from index_region where state = 1'
        ///按类型查询
        if(type) whereSql += ` and type = '${type}'`
        //按关键字模糊搜索
        if(title) whereSql += ` and title like "%${title}%"`
        SQLHelper(`
        select count(*) as total ${whereSql};
        select * ${whereSql} 
        limit ${pageSize} offset ${offset}
        `).then(ret => {
            res.send({
                total:ret[0][0].total,
                 rows:ret[1]          
            })
        })
    })

    ///新增首页项目
    ///img 图片地址 必填
    ///url 链接地址 非必填
    ///title 标题 轮播图不填，其他必填
    ///status 是否启用 非必填 1，启用  0，停用
    ///type类型 非必填 banner(默认) 轮播图, category 分类 ,recomend 为你推荐
    app.post('/admin/index',(req,res) => {
        let img = req.body.img,url = req.body.url,status = req.body.status
        let type =  req.body.type || 'banner',title = req.body.title 
        let description = req.body.description
        if(type != 'banner' && !title){
            res.send({errorMsg:'标题不能为空'})
            return ///相当于终止当前程序
        } 
        if(status != 1) status =0 ///默认启用 
        ///if(status) status = 1
        if(img){
            let createTime = new Date().getTime()
            ///字符串类型加''
            SQLHelper(`
            INSERT INTO index_region(title,img,url,description,status,state,createTime,unitId,type)
            VALUES('${title}','${img}','${url}','${description}','${status}',1,${createTime},'juzao','${type}')
            `).then(ret => {
                res.send(ret.insertId ? {_id:ret.insertId} : {errorMsg:'新增数据失败'})
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })


    ///修改首页项目
    ///indexId 对应数据库主码_id 必填
    app.put('/admin/index',(req,res) => {
        if(req.body.indexId){
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['img','url','description','title','status']
            let updateValues = [`updateTime=${updateTime}`]
            for(let i = 0;i<updateKey.length;i++){
                let key = updateKey[i],value = req.body[key]
                if(value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
            }
            SQLHelper(`UPDATE index_region set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
                res.send(ret)
            })
        }else{
            res.send({errMsg:'传入参数错误'})
        } 
    })

    ///删除地址(逻辑)
    ///addressId 主码_id 必填
    app.delete('/admin/index',(req,res) => {
        let indexId =req.query.indexId
        if(indexId){
            SQLHelper(`
            UPDATE index_region
            set state = 0
            WHERE _id = ${indexId}
            `).then(ret => {
                res.send(ret)
            })
        }else{
            res.send({errMsg:'传入参数错误'})
        }
    })

    
    ///获取首页新闻项目
    ///img 图片地址 非必填
    ///digest 摘要地址 必填
    ///title 标题 
    ///status 是否启用 非必填 1启用  0停用 
    ///type 类型 非必填   news新闻
    app.get('/admin/news', (req, res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize    //o=(n-1)*s
        SQLHelper(`
            select count(*) as total from article
            where state = 1 and type = 'news';
            select * from article 
            where state = 1 and type = 'news'
            limit ${pageSize} offset ${offset}
            `).then(ret => {
            console.log(ret)
            res.send({
                total: ret[0][0].total,
                rows: ret[1]
            })
        })

    })

    ///新增新闻项目
    ///img 图片地址 必填
    ///digest 摘要 必填
    ///title 标题 轮播图不填，其他必填
    ///status 是否启用 非必填 1启用  0停用 
    ///type 类型 非必填   banner(默认):轮播图    category:分类    recommend:为你推荐
    app.post('/admin/index/news', (req, res) => {
        let img = req.body.img, digest = req.body.digest
        let type = req.body.type || 'news', title = req.body.title
        let content = req.body.content, userId = req.body.userId
        let status = req.body.status
        if (type != 'news' && !title) {
            res.send({ errorMsg: '标题不能为空' })
            return  //终止代码执行
        }
        if (status != 1) status = 0
        if (title) {
            let createTime = new Date().getTime()
            SQLHelper(`
            INSERT INTO article(title,img,digest,state,status,createTime,unitId,type,hot,content,userId)
            VALUES('${title}','${img}','${digest}',1,'${status}',${createTime},'juzao','${type}',1,'${content}',${userId})
            `).then(ret => {
                console.log(ret)
                let _id = ret.insertId
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }

    })


    ///修改新闻项目
    ///传入indexId   ———— ( _id主码必填 )
    app.put('/admin/index/news', (req, res) => {
        if (req.body.indexId) {
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['img', 'digest', 'title', 'status', 'userId', 'content', 'hot']
            let updateValues = [`updateTime=${updateTime}`]
            for (let i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value !== undefined) updateValues.push(`${key} = '${value}'`) ///判断哪些需要修改
            }
            console.log(updateValues)
            SQLHelper(`
         UPDATE article set ${updateValues.join(',')}
         WHERE _id = ${req.body.indexId}
     `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })



    ///删除新闻   逻辑删除
    ///传入address的Id   ———— (_id主码必填)
    app.delete('/admin/index/news', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            //逻辑删除  state=0
            SQLHelper(`
                UPDATE article
                set state=0      
                WHERE _id=${indexId}
            `).then(ret => {
                res.send(ret)
            })

        } else {
            res.send({ errorMsg: '传入参数错误' })
        }

    })



    ///获取商品管理品牌
    ///img logo 必填
    ///name 品牌名称 必填
    ///sort 排序 
    ///banner 广告
    app.get('/admin/pinpai', (req, res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize    //o=(n-1)*s
        SQLHelper(`
            select count(*) as total from brand
            where state = 1;
            select * from brand 
            where state = 1
            limit ${pageSize} offset ${offset}
            `).then(ret => {
            console.log(ret)
            res.send({
                total: ret[0][0].total,
                rows: ret[1]
            })
        })

    })


    ///新增品牌项目
    ///img logo 必填
    ///name 品牌名称 必填
    ///sort 排序 
    ///banner 广告
    app.post('/admin/pinpai', (req, res) => {
        let img = req.body.img, name = req.body.name
        let sort = req.body.sort, banner = req.body.banner
        if (!name) {
            res.send({ errorMsg: '品牌名字不能为空' })
            return  //终止代码执行
        }
        if (name) {
            let createTime = new Date().getTime()
            SQLHelper(`
            INSERT INTO brand(img,name,state,createTime,unitId,sort,banner)
            VALUES('${img}','${name}',1,${createTime},'juzao',${sort},'${banner}')
            `).then(ret => {
                console.log(ret)
                let _id = ret.insertId
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }

    })


    ///修改品牌项目
    ///传入indexId   ———— ( _id主码必填 )
    app.put('/admin/pinpai', (req, res) => {
        if (req.body.indexId) {
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['img', 'name', 'sort', 'banner']
            let updateValues = [`updateTime=${updateTime}`]
            for (let i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value !== undefined) updateValues.push(`${key} = '${value}'`) ///判断哪些需要修改
            }
            console.log(updateValues)
            SQLHelper(`
         UPDATE brand set ${updateValues.join(',')}
         WHERE _id = ${req.body.indexId}
     `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })


    ///删除品牌   逻辑删除
    ///传入address的Id   ———— (_id主码必填)
    app.delete('/admin/pinpai', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            //逻辑删除  state=0
            SQLHelper(`
                UPDATE brand
                set state=0      
                WHERE _id=${indexId}
            `).then(ret => {
                res.send(ret)
            })

        } else {
            res.send({ errorMsg: '传入参数错误' })
        }

    })



    ///获取商品列表
    ///imgs 轮播图图片 非必填
    ///name 商品名称 必填
    ///brandId 品牌 必填
    ///sales 销量 非必填
    ///status 上架 非必填
    app.get('/admin/sp', (req, res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize    //o=(n-1)*s
        let name= req.query.name
        let whereSql = 'from product where state = 1'
        if (name) whereSql += ` and name like "%${name}%"`
        SQLHelper(`
            select count(*) as total from product
            where state = 1;
            select * ${whereSql}
            limit ${pageSize} offset ${offset}
            `).then(ret => {
            console.log(ret)
            res.send({
                total: ret[0][0].total,
                rows: ret[1]
            })
        })

    })


    ///新增商品列表
    ///imgs 轮播图图片 非必填
    ///name 商品名称 必填
    ///brandId 品牌 必填
    ///sales 销量 非必填
    ///status 上架 非必填
    ///description 描述 非必填
    ///specification 规格 非必填
    ///content 详细 非必填
    app.post('/admin/sp', (req, res) => {
        let imgs = req.body.imgs, name = req.body.name, description = req.body.description
        let brandId = req.body.brandId, content = req.body.content, specification = req.body.specification
        let status = req.body.status
        if (!brandId && !name) {
            res.send({ errorMsg: '品牌名字不能为空' })
            return  //终止代码执行
        }
        if (status != 1) status = 0///默认启用
        if (name) {
            let createTime = new Date().getTime()
            SQLHelper(`
            INSERT INTO product(imgs,name,state,createTime,unitId,brandId,status,description,specification,content)
            VALUES('${imgs}','${name}',1,${createTime},'juzao','${brandId}','${status}','${description}','${specification}','${content}')
            `).then(ret => {
                console.log(ret)
                let _id = ret.insertId
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }

    })


    ///修改品牌项目
    ///传入indexId   ———— ( _id主码必填 )
    app.put('/admin/sp', (req, res) => {
        if (req.body.indexId) {
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['imgs', 'name', 'brandId', 'description', 'specification', 'content', 'status']
            let updateValues = [`updateTime=${updateTime}`]
            for (let i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value !== undefined) updateValues.push(`${key} = '${value}'`) ///判断哪些需要修改
            }
            console.log(updateValues)
            SQLHelper(`
         UPDATE product set ${updateValues.join(',')}
         WHERE _id = ${req.body.indexId}
     `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })



    app.delete('/admin/sp', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            //逻辑删除  state=0
            SQLHelper(`
            UPDATE product
            set state=0      
            WHERE _id=${indexId}
        `).then(ret => {
                res.send(ret)
            })

        } else {
            res.send({ errorMsg: '传入参数错误' })
        }

    })


    ///获取单品列表
    ///pageSize每页数据量大小  每页默认10
    ///pageNum 当前页 默认从1开始
    ///type 类型 
    app.get('/admin/danpin', (req, res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize    //o=(n-1)*s
        SQLHelper(`
            select count(*) as total from sku
            where state = 1;
            select * from sku
            where state = 1
            limit ${pageSize} offset ${offset}
            `).then(ret => {
            console.log(ret)
            res.send({
                total: ret[0][0].total,
                rows: ret[1]
            })
        })
    })


    ///新增单品列表
    ///skuId SKU编码 必填
    ///salePrice 售价 必填
    ///originalPrice 原价 非必填
    ///productId 商品 必填
    ///productName 商品名称 非必填
    ///imgs 图片 非必填
    ///props 属性 必填
    ///userId 直接供应商 非必填
    ///skuSpecification 规格 非必填
    app.post('/admin/danpin', (req, res) => {
        let imgs = req.body.imgs, skuId = req.body.skuId, salePrice = req.body.salePrice, skuSpecification = req.body.skuSpecification
        let originalPrice = req.body.originalPrice, productId = req.body.productId, productName = req.body.productName
        let props = req.body.props, userId = req.body.userId
        if (!productId && !skuId) {
            res.send({ errorMsg: '单品不能为空' })
            return  //终止代码执行
        }

        if (skuId) {
            let createTime = new Date().getTime()
            SQLHelper(`
            INSERT INTO sku(imgs,skuId,salePrice,createTime,unitId,productName,productId,originalPrice,props,userId,skuSpecification)
            VALUES('${imgs}','${skuId}',${salePrice},${createTime},'juzao','${productName}','${productId}',${originalPrice},'${props}','${userId}','${skuSpecification}')
            `).then(ret => {
                console.log(ret)
                let _id = ret.insertId
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }

    })


    ///修改品牌项目
    ///传入indexId   ———— ( _id主码必填 )
    app.put('/admin/danpin', (req, res) => {
        if (req.body.indexId) {
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['imgs', 'skuId', 'salePrice', 'originalPrice', 'productId', 'productName', 'props', 'userId', 'skuSpecification']
            let updateValues = [`updateTime=${updateTime}`]
            for (let i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value !== undefined) updateValues.push(`${key} = '${value}'`) ///判断哪些需要修改
            }
            console.log(updateValues)
            SQLHelper(`
         UPDATE sku set ${updateValues.join(',')}
         WHERE _id = ${req.body.indexId}
     `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })


    app.delete('/admin/danpin', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            //逻辑删除  state=0
            SQLHelper(`
            UPDATE sku
            set state=0      
            WHERE _id=${indexId}
        `).then(ret => {
                res.send(ret)
            })

        } else {
            res.send({ errorMsg: '传入参数错误' })
        }

    })

}